trigger OutletTrigger on Account (before update, after update,after insert) 
{
    
    List<Id> outletIDList=new List<Id>();
    
    if(trigger.isUpdate)
    {
        if(trigger.isBefore)
        {
            for(Integer i = 0; i < trigger.new.size(); i++)
            {
                Account newA = trigger.new[i];
                if(newA.Active_Status__c != trigger.old[i].Active_Status__c
                    && newA.Active_Status__c == '关闭')
                {
                    newA.ClosedDate__c = System.today();
                    outletIDList.add(newA.Id);
                }
            }
            
            if(outletIDList.size()>0)//如果门店关闭，删除相应的TradeDashboardDetails对象数据    更新参与活动的状态
            {
               /* Date Ndt=Date.newInstance(Date.Today().Year(),Date.Today().month(),1);
                delete [select Id from TradeDashboardDetails__c where Outlet__c in:outletIDList 
                        and  CriticalEnabler__c != 'Coverage' and SalesMonth__c =: Ndt];
                        
               delete [select Id from SSYActivityExecutionTracking__c where OutletName__c in:outletIDList 
                         and SalesMonth__c =: Ndt];*/
                 //更新参与活动的状态        
                 List<Participator_Detail_Outlet__c> parList=new List<Participator_Detail_Outlet__c>();
                 for(Participator_Detail_Outlet__c par:[select id,Outlet_Type__c from Participator_Detail_Outlet__c 
                                                                           where ActivityStartDate__c>=:Date.today().addmonths(1) and Outlet_Name__c in:outletIDList])
                 {
                     par.Outlet_Type__c='关闭';
                     parList.add(par);
                 }  
                  if(parList.size()>0)
                      update parList;
            }   
            
            Profile prf = [Select p.Name, p.Id From Profile p where Name='System Administrator' or Name='系统管理员' LIMIT 1 ];
            if (prf.Id != UserInfo.getProfileId())
            {
                 if(trigger.old[0].OwnerId!=trigger.new[0].OwnerId)
                 {
                     boolean flag=false;
                    CommonRecursionMethod method=new CommonRecursionMethod ();
                    List<Id> idList=method.getASMBelowRoleId();
                    if(idList!=NULL)
                    {
                        for(Id uId:idList)
                        {
                            if(uId==trigger.new[0].OwnerId)
                                flag=true;
                        }
                    }
                   if(!flag)
                   {
                        trigger.new[0].OwnerId.addError('您无更改此用户的权限');
                    }
                    else
                    {
                        //更改活动相应的Owner
                        List<Participator_Detail_Outlet__c> parOutletList=[select Ownerid from Participator_Detail_Outlet__c 
                                                                                                        where OwnerId=:trigger.old[0].OwnerId];
                        for(Participator_Detail_Outlet__c pdo:parOutletList)
                            pdo.Ownerid =trigger.new[0].OwnerId;
                            
                        update parOutletList;
                        
                        List<Activity_Competition_Brand_Detail__c> acbdList=[select OwnerID from Activity_Competition_Brand_Detail__c
                                                                                                             where OwnerId=:trigger.old[0].OwnerId];
                        for(Activity_Competition_Brand_Detail__c acbd:acbdList)
                            acbd.OwnerID=trigger.new[0].OwnerId;
                            
                        update acbdList;
                    }
                 }
           }
            
            delete [select id from RoutingPlan__c where StartDateTime__c > TODAY and OutletName__c in: outletIDList];
        }
        else // isAfter
        {
            if(trigger.new[0].OwnerId != trigger.old[0].OwnerId)
            {
                string soql = 'select Id from RoutingPlan__c where StartDateTime__c > TODAY';
              
            if(trigger.new.size() > 0)
            {
                String soqlTmp = '';
                for(Integer i = 0; i < trigger.new.size(); i++)
                {
                    if(trigger.old[i].OwnerId!=trigger.new[i].OwnerId)
                    {
                            if(soqlTmp!='')
                                soqlTmp+='  or ';
                            soqlTmp += 'OutletName__c=\'' + trigger.old[i].Id +'\'';
                    
                    }
                }
                if(soqlTmp!='')
                    soql += ' and ('+soqlTmp+')';
            }
         
            List<RoutingPlan__c> deletingPlan = Database.query(soql);
            delete deletingPlan;
            
            }
        }
    }//新增
    if(trigger.isInsert)
    {
       List<ParticipatorArea__c> parList= [Select Activity_Name__c,  KA__c,Type__c,Sub_region__c,Region__c,
                                                               OutletType__c, Channel__c, Activity_Name__r.Activity_Type__c,
                                                                Area__c,IsNCOrNot__c
                                                               FROM ParticipatorArea__c 
                                                               where Activity_Name__r.Activity_Start_Date__c>=:Date.today().addMonths(1)
                                                               and Type__c!='其它'
                                                               and (Activity_Name__r.Activity_Stage__c='总部已发起活动' 
                                                                      or Activity_Name__r.Activity_Stage__c='SRTM已发起活动')];
          map<String,Participator_Detail_Outlet__c> accountList=new map<String,Participator_Detail_Outlet__c>(); 
          for(ParticipatorArea__c par:parList)           
          {
              for(Account acc:Trigger.new)
              {
                  if(acc.Active_Status__c=='正常营业' && (acc.Outlet_Type__c=='全国重点客户' || acc.Outlet_Type__c=='区域重点客户' || 
                                                                                 acc.Outlet_Type__c=='婴儿用品店' || acc.Outlet_Type__c=='目录直送店' || 
                                                                                 acc.Outlet_Type__c=='其他') && acc.Chain_Customer__c !='经销商')
                  {
                       string key=String.valueOf(acc.id)+String.valueOf(par.Activity_Name__c);
                       string regionAndKAKey=String.valueOf(acc.id)+String.valueOf(par.Activity_Name__c)+par.Type__c;
                       Participator_Detail_Outlet__c pdo=new Participator_Detail_Outlet__c();
                       pdo.Participator_Area__c=par.id;
                       pdo.Outlet_Type__c='新增';
                       pdo.Outlet_Name__c=acc.id;
                       pdo.OutletResourceType__c=par.Type__c;
                       pdo.TargetNumber__c=0;
                                 
                      if(par.Activity_Name__r.Activity_Type__c=='SSY')
                      {
                           if(par.IsNCOrNot__c==acc.With_NC_or_not__c)
                           {      
                                  if(par.KA__c !=NULL && acc.Chain_Customer__c==par.KA__c)//KA门店
                                  {
                                     CheckOutletPlace(accountList,key,pdo,par,acc);
                                  }
                                 if(acc.Chain_Customer__c==NULL && par.KA__c==NULL)//OT门店
                                 {
                                     CheckOutletPlace(accountList,key,pdo,par,acc);
                                 }
                            }
                        }
                        else if(par.Activity_Name__r.Activity_Type__c=='KA')
                        {
                             if(acc.Chain_Customer__c==par.KA__c)//KA门店
                              {
                                   CheckOutletPlace(accountList,regionAndKAKey,pdo,par,acc);
                              }
                        }
                        else if(par.Activity_Name__r.Activity_Type__c=='Region')
                        {
                            if(par.IsNCOrNot__c==acc.With_NC_or_not__c)
                            {
                               CheckOutletPlace(accountList,regionAndKAKey,pdo,par,acc);
                               if(accountList.containsKey(regionAndKAKey))//比较KA
                               {
                                   if(par.KA__c!=NULL && par.KA__c!=acc.Chain_Customer__c)
                                       accountList.remove(regionAndKAKey);
                               }
                             }
                        }
                  }
              }
          }   
          insert  accountList.values();
    }
    
    public void CheckOutletPlace(map<String,Participator_Detail_Outlet__c> insertList,string key,Participator_Detail_Outlet__c pdo,ParticipatorArea__c par,Account acc)
    {
          if(acc.OutletRegion__c==par.Region__c)//判断大区是否相等
          {
              if(par.Sub_region__c!=NULL)
              {
                  if(par.Sub_region__c==acc.OutletSubRegion__c)//判断片区是否相等
                  {
                      if(par.Area__c!=NULL)
                      {
                          if(par.Area__c==acc.OutletArea__c)
                              insertList.put(key,pdo);
                      }
                      else
                          insertList.put(key,pdo);
                  }
               }
               else
                   insertList.put(key,pdo);
          }
          if(insertList.containsKey(key))//比较渠道和门店类型
          {
              if(par.OutletType__c!=NULL && par.OutletType__c!=acc.Outlet_Type__c)
                  insertList.remove(key);
              if(par.Channel__c!=NULL && par.Channel__c!=acc.Channel__c)    
                  insertList.remove(key);
          }
    }
}